<script setup>
import { reactive, ref, watch, onMounted } from "vue";
import { useRouter } from "vue-router"
import request from '@/api/request'
import { Delete, Edit, Search, Plus, Refresh } from '@element-plus/icons-vue'
// 新增：导入ElMessage用于提示
import { ElMessage, ElMessageBox } from 'element-plus'

let router = useRouter();
const rules = reactive({})


let materialId=ref([]);
let isdisabled = ref(true) // 顶部修改按钮禁用状态
let isdisabledreove = ref(true) // 顶部删除按钮禁用状态
let isVisible = ref(false) // 对话框显示状态
let data = ref({}) // 用于传递给修改表单的数据
let title = ref("") // 对话框标题

// 新增：保存选中的完整行数据（用于修改）
let selectedRows = ref([])
// 选中项的ID数组（用于批量操作）
let shipment_history_id = ref([])

let page = ref({
    current: 1,
    size: 10,
    total: 0,
    records: []
})

let Material = ref({
    materialId: '',
    materialName: '',
    category:''
})

// 搜索
const handleSearch = () => {
    page.value.current = 1;
    loadData();
}

// 加载表格数据
let loadData = () => {
    request({
        url: '/material/index',
        method: 'get',
        params: {
            current: page.value.current,
            size: page.value.size,
            materialId: Material.value.materialId,
            materialName: Material.value.materialName,
            category:Material.value.category
        }
    }).then(res => {
        page.value = res.data
    }).catch(err => {
        ElMessage.error('数据加载失败')
    })
}

loadData();

// 刷新表格
let refTanle = () => {
    isVisible.value = false;
    loadData();
}

// 跳转到新增页面
let toInsert = () => {
    title.value = "新增物料/产品";
    isVisible.value = true;
    router.push("/material/main/insert");
}

// 修改操作（接收行数据）
let toUpdate = async(row) => {
    data.value = { ...row }; // 深拷贝选中行数据，避免直接修改原数据
    title.value = "修改物料/产品";
    isVisible.value = true;
    if(row!=null){
        data.value=row;
    }else{
        data.value=materialId.value[0];
    }
    router.push("/material/main/update");
}

// 单条删除
let toRemove = () => {
    ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let ids = materialId.value.map(item=>item.materialId)
        request({
            url: "/material/delete",
            method: "delete",
            data: ids
        }).then(res => {
            ElMessage.success('删除成功')
            loadData()
        })
    })
}
let toRemoves =(id)=>{
         ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        request({
            url: "/material/delete",
            method: "delete",
            data: [id]
        }).then(res => {
            ElMessage.success('删除成功')
            loadData()
        })
    })
}

// 表格选择事件：更新选中状态和按钮禁用状态
let fuxuankuang = (a) => {
        materialId.value=a;
} 

let formRef = ref()

// 重置
let chongzhi = () => {
    Material.value = {
        materialId: '',
        materialName: '',
        category:''
    }
    filterText.value = ''
    expandAllNodes()
    handleSearch()
}

const formData = ref({
    materialName: '',
})

// 新增成功后的回调
const handleAddSuccess = (newMaterial) => {
    page.value.records.unshift({
        id: Date.now(),
        materialId: newMaterial.Material_id,
        materialName: newMaterial.Material_name,
        specificationsAndModels: newMaterial.SpecificationsAndModels,
        unit: newMaterial.unit,
        materialOrProduct: newMaterial.Category === 'wl' ? '物料' : '产品',
        category: newMaterial.Category === 'wl' ? '物料' : '产品'
    })
    page.value.total += 1
    isVisible.value = false
    ElMessage.success('新增成功')
}

// 新增：顶部修改按钮点击事件（使用选中的行数据）
const handleTopUpdate = () => {
    if (selectedRows.value.length === 1) {
        toUpdate(selectedRows.value[0]) // 传递选中的行数据给修改方法
    }
}


</script>

<template>
    <div>
        <el-card>
            <template #header>
                <div>
                    <el-row>
                        <el-col :span="4">
                            <el-form ref="formRef" inline :model="Material">
                            <el-input 
                                v-model="Material.category" 
                                placeholder="输入关键字过滤分类"  
                                clearable 
                                style="margin-bottom: 10px;"
                                @change="handleSearch"
                            />
                        </el-form>
                        </el-col>

                        <el-col :span="20">
                            <el-form ref="formRef" inline :model="Material"
                                style="display: flex;justify-content: start;" class="card_wrap">
                                <el-form-item label="物料编码" size="default" prop="materialId" class="c_item">
                                    <el-input v-model="Material.materialId" class="sousuo"
                                        placeholder="请输入物料编码" clearable @change="handleSearch"></el-input>
                                </el-form-item>
                                <el-form-item label="物料名称" size="default" prop="materialName" class="c_item">
                                    <el-input v-model="Material.materialName" class="sousuo"
                                        placeholder="请输入物料名称" clearable @change="handleSearch"></el-input>
                                </el-form-item>
                                <el-form-item class="c_item">
                                    <template #default>
                                        <el-button type="primary" size="default" @click="handleSearch" :icon="Search">搜索</el-button>
                                        <el-button type="info" size="default" :plain=true @click="chongzhi" :icon="Refresh">重置</el-button>
                                    </template>
                                </el-form-item>
                            </el-form>

                            <div style="margin-top: 20px;">
                                <el-button @click="toInsert" type="primary" :plain="true" :icon="Plus">添加</el-button>
                                <!-- 修改：顶部修改按钮绑定新的点击事件handleTopUpdate -->
                                <el-button type="success" size="default" :plain=true @click="toUpdate(null)" :icon="Edit" 
                                    style="border:0px" :disabled="materialId.length!=1">修改</el-button>
                                <!-- 修改：顶部删除按钮绑定批量删除事件handleTopRemove -->
                                <el-button type="danger" size="default" :plain=true @click="toRemove" :icon="Delete" 
                                    style="border:0px" :disabled="!materialId">删除</el-button>
                            </div>

                            <el-table :data="page.records" border stripe @selection-change="fuxuankuang">
                                <el-table-column type="selection" width="55" />
                               <el-table-column prop="materialId" label="物料编码"/>
                               <el-table-column prop="materialName" label="物料名称"/>
                                <el-table-column prop="specificationsAndModels" label="规格型号"/>
                                <el-table-column prop="unit" label="单位"/>
                                <el-table-column prop="materialOrProduct" label="物料/产品">
                                    <!-- <el-tag :type="scope.row.materialQrpPoduct=='0' ? 'primary':'danger'">{{ scope.row.materialQrpPoduct=="0"?"物料":"产品"}}</el-tag> -->
                                </el-table-column>  
                                <el-table-column prop="category" label="所属分类"/>  
                                <el-table-column prop="isEnabled" label="是否启用" #default="scope">
                                    <el-tag :type="scope.row.isEnabled=='0' ? 'primary':'danger'">{{ scope.row.isEnabled=="0"?"是":"否"}}</el-tag>
                                </el-table-column>
                                <el-table-column prop="materialRatio" label="是否安全库存" #default="scope">
                                    <el-tag :type="scope.row.materialRatio=='0' ? 'primary':'danger'">{{ scope.row.materialRatio=="0"?"是":"否"}}</el-tag>
                                </el-table-column>
                                <el-table-column label="操作" fixed="right" width="200px">
                                    <template #default="scope">
                                        <el-button size="small" type="primary" @click="toUpdate(scope.row)" :icon="Edit">修改</el-button>
                                        <el-button size="small" type="danger" @click="toRemoves(scope.row.materialId)" :icon="Delete">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination @current-change="(val) => { page.current = val; loadData() }" 
                                v-model:currentPage="page.current"
                                :page-sizes="[2, 4, 6, 8, 10]" :page-size="page.size" :total="page.total" background>
                            </el-pagination>
                        </el-col>
                    </el-row>
                    <div style="width:800px">
                        <el-dialog :title="title" v-model="isVisible" destroy-on-close width="60%">
                            <router-view @ref-table="refTanle" :data="data">
                            </router-view>
                        </el-dialog>
                    </div>
                </div>
            </template>
        </el-card>
    </div>
</template>

<style scoped>
.sousuo {
    width: 200px;
}

.card_wrap {
    width: 98%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

.c_item {
    flex: 1;
    margin: 0px 5px 15px 0;
    width: calc((100% - 10px)/3);
    min-width: calc((100% - 10px)/3);
    max-width: calc((100% - 10px)/3);

    &:nth-child(3n) {
        margin-right: 0;
    }
}

.filter-tree :deep(.el-tree-node__content) {
    height: auto;
    padding: 5px 0;
}
</style>